package es.unileon.is.finalproyect.userinterface;

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;


import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;

import es.unileon.is.finalproyect.texts.Text;
import es.unileon.is.finalproyect.themes.Themes;
import es.unileon.is.finalproyect.users.*;

public class UserInterface extends JFrame {
	/**
	 * Launch the application.
	 */
	
	JPanel _pendingTextsLabelPanel;
	JPanel _resolvedTextsLabelPanel;
	Map<JRadioButton, Text> _pendingTextsMap;
	Map<JRadioButton, Text> _resolvedTextsMap;
	Text _selectedPendingText;
	Text _selectedResolvedText;
	
	JPanel _pendingStatisticsPanel;
	JLabel _yourScoreLabel;
	JLabel _globalAverageLabel;
	JPanel _freeChartPanel;
	JLabel _form1;
	JLabel _form2;
	
	JLabel _timeToReadLabel;
	JLabel _timeToAnswerLabel;
	
	ImageLabel _image;

	User _currentUser;
	List<Text> _pendingTextsList;
	List<Text> _resolvedTextsList;
	List<Group> _groupFilter;
	

	/**
	 * Create the frame.
	 */
	public UserInterface(User u) {
		_currentUser = u;
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(450, 300);
		setExtendedState(JFrame.MAXIMIZED_BOTH);
		initComponents();

	}
	
	private void initComponents(){
		if(_currentUser != null){
			_pendingTextsList = _currentUser.getPendingTexts();
			_resolvedTextsList = _currentUser.getResolvedTexts();
		} else {
			_pendingTextsList = new ArrayList<Text>();
			_resolvedTextsList = new ArrayList<Text>();
		}
		
		_pendingTextsMap = new HashMap<JRadioButton, Text>();
		_resolvedTextsMap = new HashMap<JRadioButton, Text>();
		_groupFilter = new ArrayList<Group>();
		
		JMenuBar jmb = new JMenuBar();
		setJMenuBar(jmb);
		
		JMenu filterMenu = new JMenu("Filter");
		filterMenu.setMnemonic('F');
		jmb.add(filterMenu);
		
		JMenuItem byGroupMenuItem = new JMenuItem("By group...");
		byGroupMenuItem.setMnemonic('g');
		filterMenu.add(byGroupMenuItem);
		
		JMenu propertiesMenu = new JMenu("Properties");
		jmb.add(propertiesMenu);
		
		JMenuItem properties = new JMenuItem("User Properties");
		properties.setMnemonic('P');
		propertiesMenu.add(properties);
		properties.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				showPropertiesDialog();
				_image.setIcon(obtainImage());
			}
		});
		JMenu logoutMenu = new JMenu("Logout");
		logoutMenu.setMnemonic('l');
		jmb.add(logoutMenu);
		JMenuItem logout = new JMenuItem("Logout");
		logoutMenu.add(logout);
		logout.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				dispose();
				new LoginInterface().setVisible(true);
			}
		});
		

		byGroupMenuItem.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				filterByGroup();				
			}
		});
		
		//*********** MODIFICACIONES THEME *******************
		JMenu menuthemes = new JMenu("Themes");
		menuthemes = Themes.showNewTheme(menuthemes, getContentPane());
		jmb.add(menuthemes);
		//****************************************************
		
		//*****modificaciones para JAVAHELP*******
		JMenu menuHelp = new JMenu("Help");
		JMenuItem help = new JMenuItem("Show help");
		jmb.add(Box.createHorizontalGlue());
		jmb.add(menuHelp);
		menuHelp.add(help);
		//metodo para dar la accion a help
		ViewHelp.showHelp(help, getContentPane(), "UsuarioInterfaz");
		//*****************************************
		
		getContentPane().setLayout(new BorderLayout());
		JPanel userInformationPanel = new JPanel();
		userInformationPanel.setPreferredSize(new Dimension(750, getHeight()));
		getContentPane().add(userInformationPanel,BorderLayout.WEST);
		
		JPanel welcomePanel = new JPanel(new GridLayout(1,2));
		userInformationPanel.add(welcomePanel, BorderLayout.NORTH);
		JLabel welcomeLabel = new JLabel("Welcome, " + _currentUser.getUserName());
		welcomePanel.add(welcomeLabel);
		
		_image = new ImageLabel(obtainImage());
		welcomePanel.add(_image);
		
		
		_freeChartPanel = new JPanel(new GridLayout(2,1));
		_form1 = new JLabel();
		BufferedImage grafic = crearChartEstadisticasGenerales();
		_form1.setIcon((Icon)new ImageIcon(grafic));
	    _freeChartPanel.add(_form1);	    
	    _form2=new JLabel();
		_form2.setIcon((Icon)new ImageIcon(crearChart()));
	    _freeChartPanel.add(_form2);
	    userInformationPanel.add(_freeChartPanel,BorderLayout.CENTER);
			
		
		JPanel textsPanel = new JPanel(new GridLayout(2,1));
		getContentPane().add(textsPanel);
		
		
		JPanel resolvedTextsPanel = new JPanel(new BorderLayout());
		textsPanel.add(resolvedTextsPanel);
		JLabel resolvedTextsLabel = new JLabel("Resolved Texts");
		resolvedTextsLabel.setHorizontalAlignment(SwingConstants.CENTER);
		resolvedTextsPanel.add(resolvedTextsLabel, BorderLayout.NORTH);
		
		JScrollPane resolvedTextsScroll = new JScrollPane();
		resolvedTextsPanel.add(resolvedTextsScroll);
		_resolvedTextsLabelPanel = new JPanel(null);
		resolvedTextsScroll.setViewportView(_resolvedTextsLabelPanel);
		
		JPanel confirmTextPanel = new JPanel(new GridLayout(1,3));
		resolvedTextsPanel.add(confirmTextPanel, BorderLayout.SOUTH);
		
		_yourScoreLabel = new JLabel("Your score: ");
		_globalAverageLabel = new JLabel("Global Average: ");
		JButton revisionButton = new JButton("Revision");
		revisionButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				reviseText();
			}
		});
		
		confirmTextPanel.add(_yourScoreLabel);
		confirmTextPanel.add(_globalAverageLabel);
		confirmTextPanel.add(revisionButton);
		
		JPanel pendingTextsPanel = new JPanel(new BorderLayout());
		textsPanel.add(pendingTextsPanel);
		JLabel pendingTextsLabel = new JLabel("Pending Texts");
		pendingTextsLabel.setHorizontalAlignment(SwingConstants.CENTER);
		pendingTextsPanel.add(pendingTextsLabel, BorderLayout.NORTH);
		JScrollPane pendingTextsScroll = new JScrollPane();
		pendingTextsPanel.add(pendingTextsScroll);
		_pendingTextsLabelPanel = new JPanel(null);
		pendingTextsScroll.setViewportView(_pendingTextsLabelPanel);
		
		_pendingStatisticsPanel = new JPanel(new GridLayout(1,3));
		pendingTextsPanel.add(_pendingStatisticsPanel, BorderLayout.SOUTH);
		
		_timeToReadLabel = new JLabel("Time to read: ");
		_timeToAnswerLabel = new JLabel("Time to answer: ");
		JButton resolveButton = new JButton("Resolve Text");

		resolveButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				resolveText();
			}
		});
		
		_pendingStatisticsPanel.add(_timeToReadLabel);
		_pendingStatisticsPanel.add(_timeToAnswerLabel);
		_pendingStatisticsPanel.add(resolveButton);
		populateResolvedPanel();
		populatePendingPanel();
		pack();
	}
	
	private void populatePendingPanel(){
		for(JRadioButton jr : _pendingTextsMap.keySet()){
			_pendingTextsLabelPanel.remove(jr);
		}
		_pendingTextsMap.clear();
		if(_currentUser != null){
			List<Text> pending = filterListByGroup( _currentUser.getPendingTexts());
			ChangeListener cl = new ChangeListener(){
				public void stateChanged(ChangeEvent evt){
					if(((JRadioButton)evt.getSource()).isSelected()){
						_selectedPendingText = _pendingTextsMap.get((JRadioButton)evt.getSource());
					} else {
						_selectedPendingText = null;
					}
					updatePendingLabels();
				}
			};
			populate(pending, _pendingTextsMap, _pendingTextsLabelPanel, cl);
		}
	}
	
	private List<Text> filterListByGroup(List<Text> originalList){
		List<Text> filteredList;
		if(_groupFilter.isEmpty()){
			filteredList = originalList;
		} else {
			List<Text> originalCopy = originalList;
			filteredList = new ArrayList<Text>();
			for(Group g : _groupFilter){
				for(Text t : originalCopy){
					if(g.hasAssigned(t)){
						filteredList.add(t);
					}
				}
			}
		}
		return filteredList;
	}
	
	private void populateResolvedPanel(){
		for(JRadioButton jr : _resolvedTextsMap.keySet()){
			_resolvedTextsLabelPanel.remove(jr);
		}
		_resolvedTextsMap.clear();
		if(_currentUser != null){
			List<Text> resolved = filterListByGroup(_currentUser.getResolvedTexts());
			ChangeListener cl = new ChangeListener(){
				public void stateChanged(ChangeEvent evt){
					if(((JRadioButton)evt.getSource()).isSelected()){
						_selectedResolvedText = _resolvedTextsMap.get(evt.getSource());
						BufferedImage grafic1 = crearChart();
					    _form2.setIcon((Icon)new ImageIcon(grafic1));
					    revalidate();
					    repaint();
					} else {
						_selectedResolvedText = null;
					}
					updateResolvedLabels();
				}
			};
			populate(resolved, _resolvedTextsMap, _resolvedTextsLabelPanel, cl);
		}
	}
	private void populate(List<Text> texts, Map<JRadioButton, Text> map, JPanel panel, ChangeListener cl){
		int y = 10;
		ButtonGroup bg = new ButtonGroup();
		for(Text t : texts){
			JRadioButton jr = new JRadioButton(t.getTitle());
			int width = (int)jr.getPreferredSize().getWidth();
			int height = (int) jr.getPreferredSize().getHeight();
			jr.setBounds(10, y, width, height);
			y += height+20;
			panel.add(jr);
			bg.add(jr);
			map.put(jr, t);
			jr.addChangeListener(cl);
		}
		panel.setPreferredSize(new Dimension(400,y));
	}
	
	private void updatePendingLabels(){
		String timeToRead = "";
		String timeToAnswer = "";
		if(_selectedPendingText != null){
			int secondsToRead = _selectedPendingText.getSecondsToRead();
			timeToRead = String.valueOf(secondsToRead/60) + " min, " + String.valueOf(secondsToRead - (secondsToRead/60)* 60) + " s";
			int secondsToAnswer = _selectedPendingText.getSecondsToAnswer();
			timeToAnswer = String.valueOf(secondsToAnswer/60) + " min, " + String.valueOf(secondsToAnswer - (secondsToAnswer/60)* 60) + " s";
		}
		_timeToReadLabel.setText("Time to read: " + timeToRead);
		_timeToAnswerLabel.setText("Time to answer: " + timeToAnswer);
	}
	
	private void updateResolvedLabels(){
		String yourScore = "";
		String globalAverage = "";
		if(_selectedResolvedText != null){
			yourScore = String.valueOf(_currentUser.getMarkToText(_selectedResolvedText));
			globalAverage = String.valueOf(_selectedResolvedText.getGlobalAverage());
		}
		_yourScoreLabel.setText("Your Score: " + yourScore);
		_globalAverageLabel.setText("Global Average: " + globalAverage);
	}
	private void reviseText(){
		if(_selectedResolvedText != null){
			new TextReviewInterface(_selectedResolvedText, _currentUser).setVisible(true);
		}
	}
	private void resolveText(){
		if(_selectedPendingText != null){
			new TextReaderInterface(_selectedPendingText, _currentUser, this, true).setVisible(true);
			populatePendingPanel();
			populateResolvedPanel();
			_form1.setIcon(new ImageIcon(crearChartEstadisticasGenerales()));
			revalidate();
			repaint();
		}
	}
	public void filterByGroup(){
		SelectGroupDialog dialog = new SelectGroupDialog(_currentUser, this, true);
		dialog.setVisible(true);
		_groupFilter = dialog.getGroupList();
		populatePendingPanel();
		populateResolvedPanel();
		revalidate();
		repaint();
	}
	
	private BufferedImage crearChart() {
		int nota = 0;
		int incorrecta = 0;
		String title = "No Stats";
		if(_selectedResolvedText != null){
					
		    nota=_currentUser.getMarkToText(_selectedResolvedText)*10;
		    incorrecta = 100-nota;
		    title = _selectedResolvedText.getTitle()+" Stats";
		    
		}
			DefaultPieDataset data=new DefaultPieDataset();
		    data.setValue("% Corrects Answers "+nota,new Double(nota));
		    data.setValue("% Wrong Answers "+(incorrecta),new Double(incorrecta));
		    
		    JFreeChart chart = ChartFactory.createPieChart(
		            title,     //Nombre del gr�fico
		            data,                   //data
		            false,                  //Leyenda
		            true,
		            false);       
		    
		    PiePlot plot = (PiePlot)chart.getPlot();
		    //Color de las etiquetas
		    plot.setLabelBackgroundPaint(Color.ORANGE);
		    //Color de el fondo del gr�fico
		    plot.setBackgroundPaint(Color.WHITE);
		    plot.setNoDataMessage("No hay data");
		 
		    return chart.createBufferedImage(300,300);
	}
	private BufferedImage crearChartEstadisticasGenerales(){
		
		int correctA = _currentUser.getCorrectAnswers();
		int wrongA = _currentUser.getWrongAnswers();
		DefaultPieDataset data=new DefaultPieDataset();
	    data.setValue("Corrects Answers "+correctA,new Double(correctA));
	    data.setValue("Wrong Answers "+wrongA,new Double(wrongA));
	    
	    JFreeChart chart = ChartFactory.createPieChart(
	            "User Global Stats",     //Nombre del gr�fico
	            data,                   //data
	            false,                  //Leyenda
	            true,
	            false);       
	    
	    PiePlot plot = (PiePlot)chart.getPlot();
	    //Color de las etiquetas
	    plot.setLabelBackgroundPaint(Color.ORANGE);
	    //Color de el fondo del gr�fico
	    plot.setBackgroundPaint(Color.WHITE);
	    plot.setNoDataMessage("No hay data");
	 
	    return chart.createBufferedImage(300,300);
	}
	
	private void showPropertiesDialog(){
		new UserPropertiesDialog(_currentUser,this,true).setVisible(true);
	}
	
	private ImageIcon obtainImage(){
		byte[] picture = _currentUser.getPicture();
		ImageIcon image = null;
		if(picture != null){
			image = new ImageIcon(_currentUser.getPicture());
		} else {
			image = new ImageIcon("img/no_user.jpg");
		}
		return image;
	}
}
